package com.efounder.widget;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.activity.MenuActivity;
import com.efounder.activity.SimpleWebFragment_url;
import com.efounder.ospmobilelib.R;
import com.efounder.utils.FilesOperationDataUtil;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;



public class ViewPagerwithGridView extends ViewPager {

    float curX = 0f;
    float downX = 0f;
    public Itemclick itemClick;
    private MenuGridRefeshInterface  menuGridRefeshInterface;


    /**
     * 保证滑动效果和主机面的滑动效果不冲突
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent arg0) {
        // TODO Auto-generated method stub
        curX = arg0.getX();
        if (arg0.getAction() == MotionEvent.ACTION_DOWN) {
            downX = curX;
        }
        return super.onInterceptTouchEvent(arg0);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        curX = event.getX();

        return super.onTouchEvent(event);
    }

    private static final int GRIDVIEW_COUNT = 4;// 声明每一页皮肤的个数

    //private List<Integer> lists = new ArrayList<Integer>();// 存储皮肤个数
    private List<View> allViews = new ArrayList<View>();// 存储页面个数
    private SkinViewPagerAdapter viewPagerAdapter;// PageAdapter对象
    private final Context context;// 上下文
    public ArrayList<HashMap<String, Object>> viewList = new ArrayList<HashMap<String, Object>>();// Activity传来的数据源
    List<View> animationList = new ArrayList<View>();
    List<RelativeLayout> delList = new ArrayList<RelativeLayout>();
    ArrayList<HashMap<String, Object>> slideList;//文件里的list
    ArrayList<HashMap<String, Object>> bottomList;//需要显示的list
    //此view的广播
    viewPagewithGridViewBroadcast viewPagewithGridViewBroadcast;
    // 利用辅助变量计算页面数
    int pageCount;

    private boolean isAnim =false;
    public ViewPagerwithGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        // 注册intentFilter
		/* viewPagewithGridViewBroadcast = new viewPagewithGridViewBroadcast();
			// 注册intentFilter
			IntentFilter filter = new IntentFilter();
			filter.addAction("uiChange");
			BroadCastutil.getinstance().addbroadCast(viewPagewithGridViewBroadcast);
			// 注册filter，连接broadcastSaveFile
			context.registerReceiver(viewPagewithGridViewBroadcast, filter);*/
    }
    /*
     * 刷新组件
     */
    public void refresh(){
        bottomList = new ArrayList<HashMap<String,Object>>();
        for(int i=0;i<slideList.size();i++){
            @SuppressWarnings("unchecked")

            HashMap<String, Object> map = slideList.get(i);
            if((Boolean)(map.get("ischecked"))==true){
                bottomList.add(0,map);
            }
        }

        viewList= new ArrayList<HashMap<String,Object>>();

        for(int k = 0 ;k<bottomList.size();k++){
            viewList.add(k,bottomList.get(k));
        }
        HashMap<String, Object> mapgrid0 = new HashMap<String, Object>();
        mapgrid0.put("images", "addapp");
        mapgrid0.put("title", "自定义");
        viewList.add(mapgrid0);
        this.update();
    }
    // 为ViewPager设置数据，必须实现包含的四个方法
    private class SkinViewPagerAdapter extends PagerAdapter {

        private SkinViewPagerAdapter() {
            ViewPagerwithGridView.this.resetData();
        }

        @Override
        public int getCount() {
            return allViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        public int getItemPosition(Object object) {
            //是viewpage重新加载
            return POSITION_NONE;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(allViews.get(position),
                    new LinearLayout.LayoutParams(
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT));
            return allViews.get(position);
        }
    }


    // 为每个单元设置数据
    private class bottomGridAdapter extends BaseAdapter {

        private Context mContext;
        private int pagePosition;
        private LayoutInflater skinInflater;

        private bottomGridAdapter(Context context, int pagePosition) {
            this.mContext = context;
            this.pagePosition = pagePosition;
            skinInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {

            int size = (viewList == null ? 0 : viewList.size() - GRIDVIEW_COUNT* pagePosition);
            if (size > GRIDVIEW_COUNT) {
                return GRIDVIEW_COUNT;
            } else {
                return size > 0 ? size : 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            // 这里本来return的是position
            return 0;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final int nowPosition = GRIDVIEW_COUNT * pagePosition + position;
            ViewHolder holder;
            if (convertView != null) {
                holder = (ViewHolder) convertView.getTag();
            } else {
                // 加载布局生成布局对象，然后取得布局中的控件，为控件设置内容
                convertView = skinInflater.inflate(R.layout.viewpager_bottomgrid_item,
                        null);
                holder = new ViewHolder();
                holder.name = (TextView) convertView
                        .findViewById(R.id.skin_popup_app_name);
                holder.icon = (ImageView) convertView
                        .findViewById(R.id.skin_popup_app_icon);
                holder.layout = (RelativeLayout) convertView
                        .findViewById(R.id.item_Rel);
                ApplicationInfo appInfo = context.getApplicationInfo();
                int ID = context.getResources().getIdentifier(String.valueOf(viewList.get(nowPosition).get("images")), "drawable", appInfo.packageName);
                Bitmap bm = BitmapFactory.decodeResource(context.getResources(), ID);
                if(bm==null){
                    int resID = context.getResources().getIdentifier("iframe_icon_refresh", "drawable", appInfo.packageName);
                    bm = BitmapFactory.decodeResource(context.getResources(), resID);
                }
                holder.icon.setImageBitmap(bm);
                holder.name.setText((String) viewList.get(nowPosition).get(
                        "title"));

                holder.del = (ImageView) convertView.findViewById(R.id.cross_icon);
                holder.del.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        String text = (String) viewList.get(nowPosition).get("title");

                        for (int i = 0; i < slideList.size(); i++) {
                            @SuppressWarnings("unchecked")
                            HashMap<String, Object> map = slideList.get(i);
                            if (map.get("title").equals(text)) {
                                map.remove("ischecked");
                                map.put("ischecked", false);
                                break;
                            }

                        }

                        FilesOperationDataUtil.clearFileData(context);

                        //edit by lch delte 8-17
                        //FilesOperationDataUtil.createFile(context, slideList);
                        //-1代表点击删除键发送的广播
                        sendBroadCast(-1);

                        viewList.remove(nowPosition);
                        update();
                    }
                });
                convertView.setTag(holder);
            }

            // 设置标题和监听
            return convertView;
        }
    }

    // 定义一个类，包含需要的每个布局和控件
    static class ViewHolder {
        RelativeLayout layout;
        ImageView icon;
        TextView name;
        ImageView del;
    }


    // 接收来自Activity的list列表
    public void setArrayList(ArrayList<HashMap<String, Object>> list) {
        this.viewList = list;
        // 为ViewPager设置Adapter
        viewPagerAdapter = new SkinViewPagerAdapter();
        this.setAdapter(viewPagerAdapter);

        this.getAdapter().notifyDataSetChanged();
    }

    public void update() {
        resetData();
        viewPagerAdapter.notifyDataSetChanged();
    }

    public void resetData() {
        pageCount =  (viewList.size()-1) / GRIDVIEW_COUNT+1;
        allViews.clear();

        // 加载每一个ViewPager页的view
        LayoutInflater inflater = LayoutInflater.from(context);
        for (int i = 0; i < pageCount; i++) {
            final int k1 = i;
            View mView = inflater.inflate(R.layout.appmenu_gridview, null);
            LinearLayout grid_container = (LinearLayout) mView.findViewById(R.id.grid_container);
            final GridView skinGridView = (GridView) mView
                    .findViewById(R.id.menu_bottom_gridview);
            WindowManager wm = (WindowManager) getContext()
                    .getSystemService(Context.WINDOW_SERVICE);

            int width = wm.getDefaultDisplay().getWidth();
            int height = wm.getDefaultDisplay().getHeight();
            skinGridView.setColumnWidth(width/5);
            if(pageCount>1&&i<pageCount){
                skinGridView.setNumColumns(GRIDVIEW_COUNT);
            }else{
                skinGridView.setNumColumns(viewList.size()-GRIDVIEW_COUNT*(pageCount-1));
            }
            skinGridView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    if(isAnim){
                        cleanAnim();
                        return ;
                    }
                    // TODO Auto-generated method stub
                    if ((k1) * GRIDVIEW_COUNT + position == viewList.size()-1) {
                        //0代表点击第一个按钮是发送的广播标记。
                        Intent intent = new Intent();
                        intent.setClass(context, MenuActivity.class);
                        context.startActivity(intent);
                    }
                    if ((k1) * GRIDVIEW_COUNT + position != viewList.size()-1) {
                        //StubObject urlWithparam = new StubObject();
                        String url;
                        Intent intent = new Intent();
                        url = (String) viewList.get((k1) * GRIDVIEW_COUNT + position).get("url");
                        intent.putExtra("url", url);
                        String title = (String) viewList.get((k1) * GRIDVIEW_COUNT + position).get("title");
                        intent.putExtra("title", title);
                        intent.setClass(context, SimpleWebFragment_url.class);
                        context.startActivity(intent);
                    }


                    for(int j=0 ;j<animationList.size();j++){
                        animationList.get(j).clearAnimation();
                        delList.get(j).setVisibility(View.INVISIBLE);
                    }

                }
            });
            skinGridView.setOnItemLongClickListener(new OnItemLongClickListener() {

                @Override
                public boolean onItemLongClick(AdapterView<?> arg0,
                                               View arg1, int arg2, long arg3) {
                    if(isAnim){
                        cleanAnim();
                        return true ;
                    }
                    isAnim = true;
                    // TODO Auto-generated method stub
                    skinGridView.setFocusable(true);
                    skinGridView.setFocusableInTouchMode(true);
                    skinGridView.requestFocus();
                    //skinGridView.requestFocus();
                    int nCount = skinGridView.getChildCount();
                    skinGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
                    if(k1 ==viewList.size()-1||k1==pageCount-1){
                        for(int i = 0 ;i < nCount-1; i ++){
                            View v = skinGridView.getChildAt(i);
                            RelativeLayout layout;
                            Animation shake;
                            if(i % 2 == 0){
                                shake = AnimationUtils.loadAnimation(
                                        context, R.anim.icon_anim_left);
                                shake.reset();
                                shake.setFillAfter(true);
                            }
                            else{
                                shake = AnimationUtils.loadAnimation(
                                        context, R.anim.icon_anim_right);
                                shake.reset();
                                shake.setFillAfter(true);
                            }
                            v.startAnimation(shake);
                            animationList.add(v);
                            layout = (RelativeLayout)v.findViewById(R.id.view_delete);
                            delList.add(layout);

                            layout.setVisibility(View.VISIBLE);
                        }
                    }else{
                        for(int i = 0 ;i < nCount; i ++){
                            View v = skinGridView.getChildAt(i);
                            RelativeLayout layout;
                            Animation shake;
                            if(i % 2 == 0){
                                shake = AnimationUtils.loadAnimation(
                                        context, R.anim.icon_anim_left);
                                shake.reset();
                                shake.setFillAfter(true);
                            }
                            else{
                                shake = AnimationUtils.loadAnimation(
                                        context, R.anim.icon_anim_right);
                                shake.reset();
                                shake.setFillAfter(true);
                            }
                            v.startAnimation(shake);
                            animationList.add(v);
                            layout = (RelativeLayout)v.findViewById(R.id.view_delete);
                            delList.add(layout);
                            layout.setVisibility(View.VISIBLE);
                        }
                    }
                    return true;
                }
            });

            skinGridView.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View arg0, boolean arg1) {
                    // TODO Auto-generated method stub


                    if(arg1){
                        Log.i("viewpagewithgrid有焦点", "有焦点");
                    }else{

                        cleanAnim();
                    }
                }
            });

            bottomGridAdapter adapter = new bottomGridAdapter(context, i);
            skinGridView.setAdapter(adapter);
            skinGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

            adapter.notifyDataSetChanged();
            allViews.add(grid_container);
        }
    }
    private void cleanAnim(){
        isAnim =false;
        for(int j=0 ;j<animationList.size();j++){
            animationList.get(j).clearAnimation();
            delList.get(j).setVisibility(View.INVISIBLE);
        }
    }
    /*
     * 文件保存成功后发送广播
     */
    public void sendBroadCast(int i) {

        String ACTION = "uiChange";
        Intent intent = new Intent();
        if(i==0){
            intent.putExtra("name", "button0");
        }else if(i==1){
            intent.putExtra("name", "button0-");
        }
        else{
            intent.putExtra("name", "del");
        }
        intent.setAction(ACTION);
        // 普通广播
        context.sendBroadcast(intent);
    }

    public class viewPagewithGridViewBroadcast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            String name = intent.getStringExtra("name");
            if("buttonclick".equals(name)){
                refresh();
            }

        }
    }

    public void setItemClick(Itemclick itemClick){
        this.itemClick = itemClick;
    }
    public interface Itemclick{
        public void itemClick(Fragment fragment);
    }
    public interface MenuGridRefeshInterface{
        public void RefeshInterface();
    }
    public MenuGridRefeshInterface getMenuGridRefeshInterface() {
        return menuGridRefeshInterface;
    }
    public void setMenuGridRefeshInterface(
            MenuGridRefeshInterface menuGridRefeshInterface) {
        this.menuGridRefeshInterface = menuGridRefeshInterface;
    }
}
